package sindconsole.webapp;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@Configuration
public class ConsoleWebapp implements WebMvcConfigurer, WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Bean
    public WebServerFactoryCustomizer containerCustomizer() {
        return (WebServerFactoryCustomizer<ConfigurableWebServerFactory>) container -> {
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
            container.addErrorPages(error404Page);
            ErrorPage error405Page = new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/index.html");
            container.addErrorPages(error405Page);
        };
    }

    @Value("${sindconsole.file-directory:files}")
    String fileDirectory;

    @Value("${sindconsole.file-context-path:/files}")
    String fileContextPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileContextPath + "/**")
                .addResourceLocations("file:" + fileDirectory + "/")
                .resourceChain(true);
        registry.addResourceHandler("/geojson/**")
                .addResourceLocations("classpath:/geojson/");
        registry.addResourceHandler("/sample/**")
                .addResourceLocations("classpath:/sample/");
    }

    @Value("${server.http-port:0}")
    int httpPort;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        if(httpPort > 0) {
            Connector httpConnector = new Connector("HTTP/1.1");
            httpConnector.setPort(httpPort);
            factory.addAdditionalTomcatConnectors(httpConnector);
        }
    }

}
